package com.suxin.event;

import com.suxin.event.error.ErrorHandler;
import com.suxin.event.error.LoggerErrorHandler;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * @author Tang
 * @classname SimpleApplicationEventMulticaster
 * @description [ 简单的事件派发者 ]
 * @date 2021/3/17 13:29
 */
@Component
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster{

    ErrorHandler errorHandler;

    public SimpleApplicationEventMulticaster() {
        errorHandler = new LoggerErrorHandler();
    }

    /**
     * 从容器中获取自己感兴趣的事件，进行异步派发
     * @param applicationEvent
     */
    @Override
    public void publish(ApplicationEvent applicationEvent) {
        Map<String, ApplicationListener> beansOfType = this.applicationContext.getBeansOfType(ApplicationListener.class);
        Set<Map.Entry<String, ApplicationListener>> entries = beansOfType.entrySet();
        for (Map.Entry<String, ApplicationListener> enrty : entries) {
            // 线程池执行
            getExecutor().execute(() -> {
                invokeListener(enrty.getValue(),applicationEvent);
            });
        }
    }

    private void invokeListener(ApplicationListener listener,ApplicationEvent applicationEvent) {
        try {
            listener.onApplicationEvent(applicationEvent);
        } catch (Exception e) {
            errorHandler.handlerError(e);
        }
    }

    public ErrorHandler getErrorHandler() {
        return errorHandler;
    }

    public void setErrorHandler(ErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }
}